//
//  editMyResumeVoiceResumeVC.swift
//  DingDongZP
//
//  Created by 三秒文化 on 16/4/15.
//  Copyright © 2016年 iyhjiang.com. All rights reserved.
//

import UIKit
import AVFoundation
import WSProgressHUD

class LDEditMyResumeVoiceResumeVC: LDBaseCustomNavTabVC {
    
    let cellTag = 1111
    
    var tapInButtonTimeInter:NSTimeInterval?
    var tapOutButtonTimeInter:NSTimeInterval?
    var currentCell:editMyResumeVoiceResumeCell?
    var preSelCell:editMyResumeVoiceResumeCell?
    
    //显示类型
    var type:LDEditMyResumeVCType?
    
    var limitMinSec:Float = 1.5
    var limitMaxSec:Float = 100.0
    var pressTime:Int = 0
    
    var cellDictArr = [Int:AnyObject]()
    
    var showHowToVoice:[String:String] = [
        
        "我的亮点":"你可以介绍说:\n“我是运营九段，产品疯子，从不揍程序员，聪明绝顶，独当一面，用户需求癖，路子野”\n等结合自己的亮点标签来提升自己的竞争力。",
        
        "我的优势":"你可以介绍说：\n“我的优势就是学习能力超强，注重细节，做走心产品”等优势来提升自己的竞争力",
        
        "工作经历":"你可以介绍说：\n“我什么时间至什么时间在哪个公司的什么部门担任什么职位，期间主要负责哪些工作。”具体工作职责可以分条说清楚，如果有多个工作经历，可以挑其中比较重要的两个或多个，并逐个描述清楚。",
        
        "教育经历":"你可以介绍说：\n“我什么时间至什么时间在某大学学的什么专业，期间主要学了什么”，如果有多个教育经历，请逐个描述清楚。"
    ]
    
    let voiceTime = "voiceTime"
    let voiceDurationKey = "voiceDuration"
    
    //
    var audioPlayer:AVAudioPlayer?
    //定时器 监测按钮 点击时长
    var timeInter:NSTimer?
    //暂时测试
    let titleArr = ["我的亮点","我的优势","工作经历","教育经历"]
    //模型数组
    var modelArr = [[String:AnyObject]]()
    
    //语音name
    var voiceNameArr = [String]()
    //语音isSet
    var voiceIsSetArr = [String]()
    //持续时间
    var vocieDurationArr = [String]()
    //上传时间
    var voiceUploadTime = [String]()
    //删除type
    var voiceDeleteType = [[String:String]]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupTableView()
    }
    
    func setupTableView() {
        
        tableView.separatorStyle = UITableViewCellSeparatorStyle.None
        tableView.contentInset = UIEdgeInsetsMake(45 + LDMargin_H * 1.5, 0, 0, 0)
        tableView.backgroundColor = LDGolbalColor.BgGoundGray
        
        let rootvc = navigationController as? LDRTRootNavVC
        
        rootvc?.tapBackNavClosure { [weak self] in
            self?.audioPlayer?.stop()
            //            self?.navigationController?.popViewControllerAnimated(true)
        }
        
    }
    
    override func viewDidAppear(animated: Bool) {
        
        requestNet()
    }
    
    override func viewDidDisappear(animated: Bool) {
        audioPlayer?.stop()
    }
    
    func requestNet() {
        
        modelArr.removeAll()
        //api 单个返回 ,只能单个解析 后续可能更改
        let infoDict = LDUserInfo.sharedInstance.myRemuseInfoDict
        let audioModel = LDMyAudioResumeModel.yy_modelWithDictionary(infoDict)
        
        let audioSet1 = audioModel?.audiohighlights_isset ?? "0"
        let audioSet2 = audioModel?.audiomystrengths_isset ?? "0"
        let audioSet3 = audioModel?.audioworkexperience_isset ?? "0"
        let audioSet4 = audioModel?.audioeduexperience_isset ?? "0"
        
        
        
        let audioDura1 = audioModel?.audiohighlights_duration ?? LDNull
        let audioDura2 = audioModel?.audiomystrengths_duration ?? LDNull
        let audioDura3 = audioModel?.audioworkexperience_duration ?? LDNull
        let audioDura4 = audioModel?.audioeduexperience_duration ?? LDNull
        
        
        let audioUpTime1 = audioModel?.audiohighlights_updated ?? LDNull
        let audioUpTime2 = audioModel?.audiomystrengths_updated ?? LDNull
        let audioUpTime3 = audioModel?.audioworkexperience_updated ?? LDNull
        let audioUpTime4 = audioModel?.audioeduexperience_updated ?? LDNull
        //        voiceUploadTime = [audioUpTime1,audioUpTime2,audioUpTime3,audioUpTime4]
        
        
        let audioName1 = infoDict["audiohighlights"] as? String ?? LDNull
        let audioName2 = infoDict["audiomystrengths"] as? String ?? LDNull
        let audioName3 = infoDict["audioworkexperience"] as? String ?? LDNull
        let audioName4 = infoDict["audioeduexperience"] as? String ?? LDNull
        //        voiceNameArr = [audioName1,audioName2,audioName3,audioName4]
        
        //删除type
        let type1 = ["type":"highlights"]
        let type2 = ["type":"mystrengths"]
        let type3 = ["type":"workexperience"]
        let type4 = ["type":"eduexperience"]
//        voiceDeleteType = [type1,type2,type3,type4]
        
        
        if type == .HeigthLightStrength {
            
            voiceIsSetArr = [audioSet1,audioSet2]
            vocieDurationArr = [audioDura1,audioDura2]
            voiceUploadTime = [audioUpTime1,audioUpTime2]
            voiceNameArr = [audioName1,audioName2]
            voiceDeleteType = [type1,type2]
            
        } else if type == .WorkExp {
            
            voiceIsSetArr = [audioSet3]
            vocieDurationArr = [audioDura3]
            voiceUploadTime = [audioUpTime3]
            voiceNameArr = [audioName3]
            voiceDeleteType = [type3]
            
        } else if type == .EduExp {
            
            vocieDurationArr = [audioDura4]
            voiceIsSetArr = [audioSet4]
            voiceUploadTime = [audioUpTime4]
            voiceNameArr = [audioName4]
            voiceDeleteType = [type4]
            
        } else {
            
            voiceIsSetArr = [audioSet1,audioSet2,audioSet3,audioSet4]
            voiceIsSetArr = [audioSet1,audioSet2,audioSet3,audioSet4]
            voiceUploadTime = [audioUpTime1,audioUpTime2,audioUpTime3,audioUpTime4]
            voiceNameArr = [audioName1,audioName2,audioName3,audioName4]
            voiceDeleteType = [type1,type2,type3,type4]
        }
        
        
        
        
        
        
        
        
        for i in 0..<voiceIsSetArr.count {
            
            var dict = [String:AnyObject]()
            dict["voiceTitle"] = titleArr[i]
            dict["voiceResumeID"] = voiceNameArr[i]
            
            if  voiceIsSetArr[i] == "1" {
                
                dict["isVoiceContent"] = true
                dict[voiceTime] = voiceUploadTime[i]
                dict[voiceDurationKey] = vocieDurationArr[i]
                modelArr.append(dict)
            } else {
                
                dict["isVoiceContent"] = false
                dict["voiceTime"] = "日期"
                modelArr.append(dict)
            }
        }
        
        tableView.reloadData()
    }
    
    // MARK: - Table view data source
    
    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        // #warning Incomplete implementation, return the number of rows
        
        return modelArr.count
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        //        if indexPath.row < 4 {
        
        var cell = tableView.dequeueReusableCellWithIdentifier("cells") as? editMyResumeVoiceResumeCell
        if cell == nil {
            cell = editMyResumeVoiceResumeCell.init(style: .Default, reuseIdentifier: "cells")
        }
        
        //            if modelArr.count == 4 {
        //
        //                let celldict = modelArr[indexPath.row] as [String:AnyObject]
        //                cell?.model = editMyResumeVoiceResumeCellModel.yy_modelWithDictionary(celldict)
        //            }
        
        
        //        var newModelArr = [NSDictionary]()
        //        if type == .HeigthLightStrength {
        //
        //            newModelArr.append(modelArr[0])
        //            newModelArr.append(modelArr[1])
        //        } else if type == .WorkExp {
        //
        //             newModelArr.append(modelArr[2])
        //        } else if type == .EduExp {
        //            newModelArr.append(modelArr[3])
        //
        //        } else {
        //            return cell!
        //        }
        
        cell?.model = editMyResumeVoiceResumeCellModel.yy_modelWithDictionary(modelArr[indexPath.row] as [NSObject : AnyObject])
        cell?.delegate = self
        cell?.tag = indexPath.row + cellTag
        return cell!
        
        //        } else {
        //
        //            var cell = tableView.dequeueReusableCellWithIdentifier("cells") as? editMyResumeVoiceResume_hiddenSwitch
        //            if cell == nil {
        //                cell = editMyResumeVoiceResume_hiddenSwitch.init(style: .Default, reuseIdentifier: "cells")
        //            }
        //            return cell!
        //        }
        
    }
    
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        if indexPath.row < 4 {
            return 180
        } else {
            return 60
        }
    }
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        let cell = tableView.cellForRowAtIndexPath(indexPath) as? editMyResumeVoiceResumeCell
        currentCell = cell
        
    }
    
    func getApi(key:String) ->String{
        
        let urlStr = LDJobfinderAPI.download.audio.baseAudioUrl + key
        
        return urlStr
    }
    
    
    func playVocie(api:String) {
        
        LDUserInfoNet.sharedInstance.queryExpectJobVoice(api, success: {
            [weak self]
            (fileData) in
            //            print((fileData?.length)!/1024)
            if fileData == nil {
                return
            }
            
            self?.audioPlayer = try? AVAudioPlayer.init(data: fileData!)
            self?.audioPlayer?.delegate = self
            self?.audioPlayer?.prepareToPlay()
            self?.audioPlayer?.numberOfLoops = 0
            self?.audioPlayer?.play()
            
        }) { (error) in
            //            print(error)
        }
    }
    
    func completeVocieData(filedata:NSData) {
        
        
        let index = (currentCell?.tag)! - cellTag
        let strKey = voiceNameArr[index]
        let isSetVocie = voiceIsSetArr[index]
        
        var voiceUrl = [String]()
        if type == .HeigthLightStrength {
            
            voiceUrl = [LDJobfinderAPI.upload.audio.highlights,LDJobfinderAPI.upload.audio.mystrengths]
        } else if type == .WorkExp {
            
            voiceUrl = [LDJobfinderAPI.upload.audio.workexperience]
        } else if type == .EduExp {
            
            voiceUrl = [LDJobfinderAPI.upload.audio.eduexperience]
        } else {
            LDShowHUB.shareInstance.showErr("错误")
        }
        
        
        
        let apiStr = voiceUrl[index]
        
        let dureation = String(format:"%d",pressTime)
        
        if isSetVocie == "1" {
            
            showLDAlertView("语音简历已经存在，是否替换", sure: { [weak self] in
                
                self?.uploadVocieData(apiStr, params: ["duration":dureation], filedata: filedata)
                }, cancel: nil)
            
        } else {
            
            uploadVocieData(apiStr, params: ["duration":dureation], filedata: filedata)
        }
        
    }
    
    //上传语音
    func uploadVocieData(apiStr:String, params:[String:String], filedata:NSData) {
        
        //        let timestr = getNowDateFormUnix()
        LDShowHUB.shareInstance.showStaus("上传中")
        
        DDNetWorkManager.shareManager().UPLOAD_VOICE(apiStr, parameters: params, filesDatas: filedata, success: {
            [weak self] (value) in
            
            if self == nil {
                return
            }
            
            LDUserInfo.sharedInstance.updataJobFinderMyResume({ (dict) in
                
                dispatch_async(dispatch_get_main_queue(), {
                    
                    self?.requestNet()
                    
                })
                
                }, failure: nil)
            
            LDUserInfoNet.sharedInstance.updateExpectJobVoice(apiStr, success: { (fileData) in
                //                print("succ,succ")
                }, failure: { (error) in
                    //                    print("fail,fail")
            })
            
            self?.requestNet()
            LDShowHUB.shareInstance.showSucc("上传成功")
            //            self?.modelArr.removeAll()
            
        }) { [weak self] (data, error) in
            
            LDShowHUB.shareInstance.showErr("上传失败")
            self?.tableView.reloadData()
        }
    }
}
extension LDEditMyResumeVoiceResumeVC:editMyResumeVoiceResumeCellDelegate {
    
    //** 开始录音 */
    func startRecord(cell:editMyResumeVoiceResumeCell) {
        
        currentCell = cell
        self.currentCell?.voiceBtn?.hidden = true
        self.currentCell?.voiceBtnPlaceHold?.hidden = true
        
        tapInButtonTimeInter = CACurrentMediaTime()
        currentCell?.audioRecorder?.startRecord()
    }
    //** 完成录音 */
    func finishRecord(cell:editMyResumeVoiceResumeCell) {
        
        pressTime = 0
        tapOutButtonTimeInter = CACurrentMediaTime()
        pressTime = Int(tapOutButtonTimeInter!) - Int(tapInButtonTimeInter!)
        if pressTime < 3 {
            LDShowHUB.shareInstance.showErr("录音时间过短...")
        }
        tableView.reloadData()
    }
    //** 取消录音 */
    func cancelRecord(cell:editMyResumeVoiceResumeCell) {
        LDShowHUB.shareInstance.dissmiss()
        requestNet()
        tableView.reloadData()
    }
    
    /** 完成录音文件转换 */
    func sendVoiceData(cell:editMyResumeVoiceResumeCell,data:NSData) {
        
        guard pressTime < 3 else {
            completeVocieData(data)
            return
        }
    }
    /** 删除录音 */
    func tapDeleteBtn(cell:editMyResumeVoiceResumeCell) {
        
        let index = cell.tag - cellTag
        let dict = voiceDeleteType[index]
        
        showLDAlertView("确定要删除？", sure: {
            
            LDUserInfoNet.sharedInstance.deleteMyResumeVocie(dict, success: { [weak self] (fileData) in
                LDShowHUB.shareInstance.showSucc("删除成功")
                
                LDUserInfo.sharedInstance.updataJobFinderMyResume({ (dict) in
                    
                    NSOperationQueue.mainQueue().addOperationWithBlock({
                        self?.requestNet()
                    })
                }, failure: nil)
                
            }) { (error) in
                LDShowHUB.shareInstance.showErr("删除失败")
            }
            
            
            }, cancel: nil)
        
        
    }
    
    //播放
    func selectedVoiceBtn(cell:editMyResumeVoiceResumeCell) {
        
        cell.voiceBtn?.animaPlay()
        currentCell = cell
        
        if preSelCell != cell {
            
            preSelCell?.voiceBtn?.animaStop()
        } else {
            
            audioPlayer?.stop()
        }
        audioPlayer?.stop()
        preSelCell = cell
        
        let index = (cell.tag) - cellTag
        let strKey = voiceNameArr[index]
        
        if strKey == LDNull {
            LDShowHUB.shareInstance.showErr("读取文件失败")
            return
        }
        
        let api = getApi(voiceNameArr[index])
        //        print(api,"voice-api")
        playVocie(api)
    }
    //停止
    func noSelectVocieBtn(cell:editMyResumeVoiceResumeCell) {
        
        //        print("停止")
        cell.voiceBtn?.animaStop()
        audioPlayer?.stop()
    }
    
    //how to say
    func showHowToSayMyVoiceResume(cell: editMyResumeVoiceResumeCell) {
        
        let index = cell.tag - cellTag
        
        showLDAlertView(titleArr[index], info: showHowToVoice[titleArr[index]] ?? "")
        
    }
    
}
extension LDEditMyResumeVoiceResumeVC:AVAudioPlayerDelegate {
    
    func audioPlayerDidFinishPlaying(player: AVAudioPlayer, successfully flag: Bool) {
        currentCell?.voiceBtn?.animaStop()
    }
}